<template>
  <div :class="{'cantEdit':!isEdit}">
    <el-upload
      class="upload-demo"
      :action="`${VUE_APP_API}/jcdSys/jcdDataUpload/fileUpload`"
      :on-preview="handlePreview"
      :on-remove="handleRemove"
      :before-upload="beforeUpload"
      :on-success="handleUploadSuccess"
      :on-error="handleUploadError"
      :multiple="true"
      :limit="maxCount"
      :on-exceed="handleExceed"
      :file-list="fileList"
      :disabled="!isEdit"
      :data="dataObj"
    >
      <el-button v-if="isEdit" size="small" type="primary">点击上传</el-button>
      <div slot="tip" class="el-upload__tip">{{ isEdit ? hint : '（点击文件可下载）' }}</div>
    </el-upload>
    <el-dialog
      title="查看图片"
      :width="'700px'"
      :modal="false"
      :visible.sync="dialogData.dialogVisible"
    >
      <img style="display: block; max-width: 600px; margin: 0 auto;" :src="dialogData.value" />
    </el-dialog>
  </div>
</template>
<script>
import store from '@/store'
import { mapState, mapActions } from 'vuex'
const VUE_APP_API = process.env.VUE_APP_API
const VUE_APP_FILE = process.env.VUE_APP_FILE

export default {
  name: 'FileUpload',
  props: {
    // 文件数组
    value: {
      type: String,
      default: ''
    },
    // 最大上传图片数量
    maxCount: {
      type: Number,
      default: 1
    },
    // 提示
    hint: {
      type: String,
      default: ''
    },
    // 是否可编辑
    isEdit: {
      type: Boolean,
      default: true
    }
  },
  data() {
    return {
      //上传的额外附加参数
      dataObj: {
        // 'login-token': ''
      },
      VUE_APP_API,
      dialogData: {
        dialogVisible: false,
        value: '',
        id: ''
      }
    }
  },
  computed: {
    // 文件列表
    fileList() {
      if (
        this.value !== undefined &&
        this.value !== '' &&
        this.value !== null
      ) {
        let fileArr = []
        let valArr = this.value.split(',')
        for (let i = 0; i < valArr.length; i++) {
          let item = valArr[i]
          let arr = item.split('/file/')
          let name = arr[arr.length - 1]
          fileArr.push({
            name,
            url: item
          })
        }
        this.$emit('change', fileArr)
        return fileArr
      } else {
        this.$emit('change', [])
        return []
      }
    }
  },
  methods: {
    ...mapActions('d2admin/account', ['logout']),
    // 修改父组件value值
    emitInput(valueArr) {
      this.$emit('input', valueArr.join(','))
    },
    // 点击删除
    handleRemove(file, fileList) {
      let valueArr = []
      for (let i = 0; i < fileList.length; i++) {
        let item = fileList[i]
        valueArr.push(item.url)
      }
      this.emitInput(valueArr)
    },
    /* 文件类型是否为图片 */
    isImg(val) {
      let fileType = val.substring(val.lastIndexOf('.') + 1)
      switch (fileType) {
        case 'png':
          return true
        case 'jpg':
          return true
        case 'jpeg':
          return true
        case 'ico':
          return true
        case 'bmp':
          return true
        case 'gif':
          return true
        case 'raw':
          return true
        case 'tif':
          return true
        default:
          return false
      }
    },
    // 点击文件
    handlePreview(file) {
      console.log(file)
      if (this.isImg(file.name)) {
        // 图片打开预览
        console.log(true)
        this.dialogData.dialogVisible = true
        this.dialogData.value = VUE_APP_FILE + file.url
      } else if (file.url) {
        console.log(false)
        // 文件下载
        const a = document.createElement('a')
        a.href = `${VUE_APP_API}/jcdSys/jcdDataUpload/fileDownLoad?filePath=${file.url.replace(
          VUE_APP_FILE,
          ''
        )}`
        a.click()
      }
    },
    // 上传文件之前操作
    beforeUpload(file) {
      // this.dataObj['login-token'] = util.cookies.get('token')
    },
    // 上传成功回调
    handleUploadSuccess(res, file) {
      let resUrl = res.data.replace(',', '')
      let newArr = []
      if (this.value !== null && this.value.length > 0) {
        let valueArr = this.value.split(',')
        newArr = valueArr.concat([resUrl])
      } else {
        newArr = [resUrl]
      }

      this.emitInput(newArr)
    },
    // 上传失败回调
    handleUploadError(err, file, fileList) {
      let res = JSON.parse(err.message)
      if (res.code === '401') {
        this.$confirm('您的登录信息已过期，请重新登录', {
          confirmButtonText: '重新登录',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.$nextTick(() => {
            this.logout()
          })
        })
      } else {
        this.$message({
          message: res.message,
          type: 'warning',
          duration: 3000
        })
      }
    },
    // 超过文件上传数量限制回调
    handleExceed(files, fileList) {
      this.$message({
        message: '最多只能上传' + this.maxCount + '个文件',
        type: 'warning',
        duration: 3000
      })
    }
  }
}
</script>
<style scoped>
.cantEdit >>> .el-upload {
  display: block;
}
.cantEdit a {
  outline: none;
}
</style>

